<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">Product Configuration Management</h2>
        <p class="page-description">Manage the mapping relationship between coin amounts and product IDs for card sales</p>
      </div>
      <div class="header-right">
        <el-button
          type="primary"
          @click="handleAddConfig"
          :icon="Plus"
        >
          Add Product Config
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span>Product Configuration List</span>
            <el-button
              type="success"
              size="small"
              @click="handleSaveAll"
              :loading="saving"
              :disabled="!hasChanges"
            >
              <el-icon><Check /></el-icon>
              Save All Changes
            </el-button>
          </div>
        </template>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <p>Loading product configurations...</p>
        </div>

        <!-- 配置表格 -->
        <div v-else>
          <!-- 提示信息 -->
          <el-alert
            title="Configuration Instructions"
            type="info"
            show-icon
            :closable="false"
            class="config-alert"
          >
            <p>• Coin Amount: The amount of coins (M) after dividing user recharge amount by 5.5, decimals supported</p>
            <p>• Product ID: Corresponding merchant product number, must be unique</p>
            <p>• Status: Only enabled configurations will take effect during card sales</p>
            <p>• Sort Order: Determines display order, smaller numbers appear first</p>
          </el-alert>

          <!-- 配置表格 -->
          <el-table
            :data="configs"
            stripe
            style="width: 100%; margin-top: 20px;"
            :loading="saving"
          >
            <el-table-column label="Sort" width="80" align="center">
              <template #default="{ row, $index }">
                <el-input-number
                  v-model="row.sortOrder"
                  :min="0"
                  :max="999"
                  size="small"
                  controls-position="right"
                  @change="handleDataChange"
                />
              </template>
            </el-table-column>

            <el-table-column label="Coin Amount (M)" width="150">
              <template #default="{ row, $index }">
                <el-input-number
                  v-model="row.coinAmount"
                  :min="0.01"
                  :max="9999"
                  :precision="2"
                  :step="0.01"
                  size="small"
                  controls-position="right"
                  placeholder="Coin Amount"
                  style="width: 100%;"
                  @change="handleDataChange"
                />
              </template>
            </el-table-column>

            <el-table-column label="Product ID" width="120">
              <template #default="{ row, $index }">
                <el-input-number
                  v-model="row.productId"
                  :min="1"
                  :max="999999"
                  size="small"
                  controls-position="right"
                  placeholder="Product ID"
                  style="width: 100%;"
                  @change="handleDataChange"
                />
              </template>
            </el-table-column>

            <el-table-column label="Description" min-width="150">
              <template #default="{ row, $index }">
                <el-input
                  v-model="row.description"
                  size="small"
                  placeholder="Product Description"
                  maxlength="100"
                  show-word-limit
                  @input="handleDataChange"
                />
              </template>
            </el-table-column>

            <el-table-column label="Status" width="100" align="center">
              <template #default="{ row, $index }">
                <el-switch
                  v-model="row.isActive"
                  active-text="Active"
                  inactive-text="Inactive"
                  @change="handleDataChange"
                />
              </template>
            </el-table-column>

            <el-table-column label="Actions" width="120" align="center" fixed="right">
              <template #default="{ row, $index }">
                <el-button
                  type="danger"
                  size="small"
                  text
                  @click="handleDeleteConfig($index)"
                  :icon="Delete"
                >
                  Delete
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 空状态 -->
          <el-empty
            v-if="configs.length === 0 && !loading"
            description="No product configurations"
            :image-size="120"
          >
            <el-button type="primary" @click="handleAddConfig">Add First Configuration</el-button>
          </el-empty>
        </div>
      </el-card>

      <!-- 快速操作卡片 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon><Setting /></el-icon>
                <span>Quick Configuration</span>
              </div>
            </template>

            <div class="quick-config">
              <p>Quick initialization based on current default product configurations:</p>
              <el-button
                type="primary"
                @click="handleQuickInit"
                :loading="quickInitLoading"
                style="margin-top: 10px;"
              >
                Initialize Default Configs
              </el-button>
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon><InfoFilled /></el-icon>
                <span>Operation Tips</span>
              </div>
            </template>

            <div class="tips-content">
              <ul>
                <li>Changes take effect only after clicking "Save All Changes"</li>
                <li>Coin amounts and product IDs must be unique, no duplicates allowed</li>
                <li>Only enabled configurations will be used during card sales</li>
                <li>Please ensure no related orders are being processed before deleting configurations</li>
              </ul>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Delete,
  Check,
  Loading,
  Setting,
  InfoFilled
} from '@element-plus/icons-vue'
import { trpc } from '../utils/trpc'

// 产品配置接口
interface ProductConfig {
  id?: number
  coinAmount: number
  productId: number
  isActive: boolean
  description?: string
  sortOrder: number
}

// 响应式数据
const loading = ref(true)
const saving = ref(false)
const quickInitLoading = ref(false)
const configs = ref<ProductConfig[]>([])
const originalConfigs = ref<ProductConfig[]>([])

// 是否有未保存的更改
const hasChanges = computed(() => {
  return JSON.stringify(configs.value) !== JSON.stringify(originalConfigs.value)
})

/**
 * 加载产品配置列表
 */
async function loadConfigs() {
  try {
    loading.value = true
    const result = await trpc.admin.getProductConfigs.query()

    if (result.success) {
      configs.value = result.data || []
      originalConfigs.value = JSON.parse(JSON.stringify(result.data || []))
    } else {
      ElMessage.error(result.message || 'Failed to load product configurations')
    }
  } catch (error) {
    console.error('Failed to load product configurations:', error)
    ElMessage.error('Failed to load product configurations, please check network connection')
  } finally {
    loading.value = false
  }
}

/**
 * 添加新的产品配置
 */
function handleAddConfig() {
  const newConfig: ProductConfig = {
    coinAmount: 1,
    productId: 1,
    isActive: true,
    description: '',
    sortOrder: configs.value.length
  }
  configs.value.push(newConfig)
  handleDataChange()
}

/**
 * 删除产品配置
 */
function handleDeleteConfig(index: number) {
  ElMessageBox.confirm(
    'Are you sure you want to delete this product configuration? This action cannot be undone.',
    'Confirm Deletion',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).then(() => {
    configs.value.splice(index, 1)
    handleDataChange()
    ElMessage.success('Configuration deleted successfully')
  }).catch(() => {
    // User cancelled deletion
  })
}

/**
 * 数据变更处理
 */
function handleDataChange() {
  // Trigger reactive update for hasChanges calculation
}

/**
 * 验证配置数据
 */
function validateConfigs(): boolean {
  if (configs.value.length === 0) {
    ElMessage.error('At least one product configuration is required')
    return false
  }

  // Check coin amount uniqueness
  const coinAmounts = configs.value.map(c => c.coinAmount)
  const uniqueCoinAmounts = new Set(coinAmounts)
  if (coinAmounts.length !== uniqueCoinAmounts.size) {
    ElMessage.error('Coin amounts cannot be duplicated')
    return false
  }

  // Check product ID uniqueness
  const productIds = configs.value.map(c => c.productId)
  const uniqueProductIds = new Set(productIds)
  if (productIds.length !== uniqueProductIds.size) {
    ElMessage.error('Product IDs cannot be duplicated')
    return false
  }

  // Check validity of each configuration
  for (let i = 0; i < configs.value.length; i++) {
    const config = configs.value[i]

    if (!config.coinAmount || config.coinAmount <= 0) {
      ElMessage.error(`Row ${i + 1}: Coin amount must be greater than 0`)
      return false
    }

    if (!config.productId || config.productId <= 0) {
      ElMessage.error(`Row ${i + 1}: Product ID must be greater than 0`)
      return false
    }

    if (config.sortOrder < 0) {
      ElMessage.error(`Row ${i + 1}: Sort order cannot be negative`)
      return false
    }
  }

  return true
}

/**
 * 保存所有配置
 */
async function handleSaveAll() {
  if (!validateConfigs()) {
    return
  }

  try {
    saving.value = true

    const result = await trpc.admin.updateProductConfigs.mutate({
      configs: configs.value
    })

    if (result.success) {
      ElMessage.success('Product configuration saved successfully')
      // Update original data, reset change status
      originalConfigs.value = JSON.parse(JSON.stringify(configs.value))
      await loadConfigs() // Reload to get latest data
    } else {
      ElMessage.error(result.message || 'Save failed')
    }
  } catch (error) {
    console.error('Failed to save product configuration:', error)
    ElMessage.error('Save failed, please check network connection')
  } finally {
    saving.value = false
  }
}

/**
 * 快速初始化默认配置
 */
function handleQuickInit() {
  ElMessageBox.confirm(
    'This will initialize the system with default product configurations. Continue?',
    'Quick Initialization',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'info',
    }
  ).then(async () => {
    try {
      quickInitLoading.value = true

      // Default configuration data (50K changed to 0.5M)
      const defaultConfigs: ProductConfig[] = [
        { coinAmount: 0.5, productId: 15, description: '0.5M Coins', sortOrder: 1, isActive: true },
        { coinAmount: 2, productId: 16, description: '2M Coins', sortOrder: 2, isActive: true },
        { coinAmount: 5, productId: 38, description: '5M Coins', sortOrder: 3, isActive: true },
        { coinAmount: 10, productId: 17, description: '10M Coins', sortOrder: 4, isActive: true },
        { coinAmount: 20, productId: 39, description: '20M Coins', sortOrder: 5, isActive: true },
        { coinAmount: 40, productId: 40, description: '40M Coins', sortOrder: 6, isActive: true },
        { coinAmount: 50, productId: 41, description: '50M Coins', sortOrder: 7, isActive: true },
        { coinAmount: 55, productId: 19, description: '55M Coins', sortOrder: 8, isActive: true },
        { coinAmount: 100, productId: 18, description: '100M Coins', sortOrder: 9, isActive: true },
        { coinAmount: 350, productId: 20, description: '350M Coins', sortOrder: 10, isActive: true },
      ]

      const result = await trpc.admin.updateProductConfigs.mutate({
        configs: defaultConfigs
      })

      if (result.success) {
        ElMessage.success('Default configuration initialized successfully')
        await loadConfigs()
      } else {
        ElMessage.error(result.message || 'Initialization failed')
      }
    } catch (error) {
      console.error('Quick initialization failed:', error)
      ElMessage.error('Initialization failed, please check network connection')
    } finally {
      quickInitLoading.value = false
    }
  }).catch(() => {
    // User cancelled initialization
  })
}

// Load configurations when page is mounted
onMounted(() => {
  loadConfigs()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.card-header .el-icon {
  margin-right: 8px;
}

.config-alert {
  margin-bottom: 20px;
}

.config-alert p {
  margin: 4px 0;
  font-size: 13px;
  line-height: 1.5;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #909399;
}

.loading-icon {
  font-size: 32px;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.quick-config {
  text-align: center;
}

.quick-config p {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.tips-content ul {
  margin: 0;
  padding-left: 20px;
}

.tips-content li {
  margin-bottom: 8px;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-right {
    justify-content: center;
  }

  .page-title {
    font-size: 20px;
    text-align: center;
  }

  .page-description {
    text-align: center;
  }
}
</style>